import os
import threading
from tempfile import TemporaryDirectory


class InputDate(object):
    def read(self):
        raise NotImplementedError

    @classmethod
    def generate_inputs(cls, config):
        raise NotImplementedError


class PathInputDate(InputDate):
    def __init__(self, path):
        super().__init__()
        self.path = path

    def read(self):
        return open(self.path).read()

    @classmethod
    def generate_inputs(cls, config):
        data_dir = config['data_dir']
        for name in os.listdir(data_dir):
            yield cls(os.path.join(data_dir, name))
        


class Worker(object):
    def __init__(self, input_data):
        self.input_data = input_data
        self.result = None

    def map(self):
        raise NotImplementedError

    def reduce(self, other):
        raise NotImplementedError

    @classmethod
    def create_workers(cls, input_class, config):
        workers = []
        for input_data in input_class.generate_inputs(config):
            print(input_data)
            workers.append(cls(input_data))
        return workers


class LineCountWorker(Worker):
    def map(self):
        data = self.input_data.read()
        print(data)
        self.result = data.count('\n')

    def reduce(self, other):
        self.result += other.result


def execute(wokers):
    threads = [threading.Thread(target=w.map) for w in wokers]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    first, rest = wokers[0], wokers[1:]
    for worker in rest:
        first.reduce(worker)

    return first.result


def mapreduce(worker_class, input_class, config):
    workers = worker_class.create_workers(input_class, config)
    return execute(workers)


def write_test_file(tmpdir):
    # ...
    fs = None
    try:
        fs = open(tmpdir+"/abc.txt", 'w')
        for _ in range(10):
            fs.writelines("1234567890\n")
    except Exception as e:
        print(str(e))
    finally:
        fs.close()

# 


if __name__ == "__main__":
    with TemporaryDirectory() as tmpdir:
        print(tmpdir)
        write_test_file(tmpdir)
        config = {'data_dir': tmpdir}
        result = mapreduce(LineCountWorker, PathInputDate, config)
    # result = mapreduce("/Users/ulysses/PycharmProjects/pythonStudy/00KnowledgePoint")
        print('There ara ', result, 'lines')
